package com.lean.android.ad.core.splash

import android.view.ViewGroup
import androidx.annotation.RestrictTo
import com.bytedance.sdk.openadsdk.CSJSplashAd
import com.lean.android.ad.core.AdRenderCallback
import com.lean.android.ad.core.AdRenderer
import com.lean.android.ad.repository.ReportHelper
import com.lean.android.ad.repository.ReportHelper.toCpmInt
import com.lean.android.ad.utils.DisplayHelper

@RestrictTo(RestrictTo.Scope.LIBRARY)
class SplashRender(private val adContainer: ViewGroup) : AdRenderer<SplashAd, AdRenderCallback> {

    override fun render(ad: SplashAd, renderCallback: AdRenderCallback) {
        ad.splashAd.setSplashAdListener(object : CSJSplashAd.SplashAdListener {
            override fun onSplashAdShow(csjSplashAd: CSJSplashAd) {
                ad.splashAd.mediationManager?.showEcpm?.also { cpmInfo ->
                    val cpm = cpmInfo.ecpm.toCpmInt()
                    val adPosition = if(ad.coldLaunch) ReportHelper.AdPositionType.Splash else ReportHelper.AdPositionType.ReSplash

                    ReportHelper.reportAdEvent(
                        requestId = ad.requestId,
                        eventType = ReportHelper.AdEventType.AdShowed,
                        platformId = cpmInfo.sdkName.orEmpty(),
                        adPosition = adPosition,
                        cpm = cpm
                    )
                }
                renderCallback.onAdShow(ad, 0, 0)
            }

            override fun onSplashAdClick(csjSplashAd: CSJSplashAd) {
                renderCallback.onAdClicked(ad)
            }

            override fun onSplashAdClose(csjSplashAd: CSJSplashAd, p1: Int) {
                renderCallback.onAdClosed(ad)
            }
        })

        val adView = ad.adView ?: return
        DisplayHelper.removeFromParent(adView)
        adContainer.removeAllViews()
        adContainer.addView(adView)
    }
}